<template>
    <div class="seat-wrap">
        <el-button type="primary" v-if="showDownload" @click="downloadExcel">打印座次表</el-button>
        <div
            id="luckysheet"
            style="margin:0px;padding:0px;position:absolute;width:100%;height: 500px;left: 10px;top: 50px;bottom:0px;"
        ></div>
    </div>
</template>

<script>
import { getOpenDownloadUrl } from "../api/common/attachment";
import request from '@/utils/request'
import LuckyExcel from 'luckyexcel'
let exportExcelFunction;
async function loadExportExcel() {
  if (!exportExcelFunction) {
    // 动态导入 '../utils/export' 模块
    const module = await import('hc-core/utils/export');
    // 从模块中获取 exportExcel 函数
    exportExcelFunction = module.exportExcel;
  }
  return exportExcelFunction;
}
import { getVacationPerson } from '../api/commonApi'
export default {
    props: {
        value: {
            type: String
        },
        meetingPerson: {
            type: String
        },
        seatingPxfs: {
            type: String
        },
        formParam: {
            type: Object
        }
    },
    data () {
        return {
            cellData: [],
            map: [],
            // excel数据
            sheets: [],
            // 选择的人员分布区域
            selectRange: [],
            personList: [],
            showDownload: false,
            // 请假人员
            vacationPersons: []
        }
    },
    watch: {
          $route: {
            handler: function (route)
            {
                console.log(route, 'route')
                if (route && route.path.indexOf('/hykq') != -1)
                {
                    this.showDownload = true
                }
                else
                {
                    this.showDownload = false
                }
            },
            immediate: true
        },
        value: {
            handler(newVal)
            {
                console.log(newVal, 'newVal')
                if (newVal)
                {
                    this.getVacationPerson()
                    this.loadExcel(newVal)
                }
            },
            immediate: true,
        },
        meetingPerson: {
            handler(newVal,oldVal) 
            {
                console.log("监听选择人员编号",newVal,'meetingPerson')
                if ((oldVal || newVal) && newVal != oldVal)
                {
                    console.log(11)
                    this.addValue(newVal)
                }
            },
            immediate: true
        },
        seatingPxfs: {
            handler(newVal, oldVal) 
            {
                console.log(newVal, oldVal, '排列方式')
                if ((oldVal || newVal) && newVal != oldVal)
                {
                    this.seatingOrder(newVal)
                }
            },
            immediate: true
        }
    },
    methods: {
        // 获取会议请假人员
        getVacationPerson()
        {
            getVacationPerson({unid: this.formParam.unid}).then(res => {
                this.vacationPersons = res.result || []
            })
        },
        // 下载座次表
        async downloadExcel()
        {
            const exportExcel = await loadExportExcel();
            exportExcel(window.luckysheet.getAllSheets(),"会议座次表")
        },
        loadExcel(fileId)
        {
            let requestParams = {
                url: getOpenDownloadUrl(fileId),
                method: "get",
                responseType: 'blob'
            };
            //执行请求
            request(requestParams).then(res => {
                var files = []
                let file = null
                if (res instanceof Blob)
                {
                    file = new File([res], 'test.xlsx', {type: res.type})
                    files.push(file)
                }
                else if (res.data instanceof Blob)
                {
                    file = new File([res.data], 'test.xlsx', {type: res.data.type})
                    files.push(file)
                }
                this.uploadExcel(files)
            })
        },
        uploadExcel(evt)
        {
            const files = evt;
            console.log(files, 'files')
            if(files==null || files.length==0){
                alert("No files wait for import");
                return;
            }

            let name = files[0].name;
            let suffixArr = name.split("."), suffix = suffixArr[suffixArr.length-1];
            if(suffix!="xlsx"){
                alert("Currently only supports the import of xlsx files");
                return;
            }
            let _this = this;
            LuckyExcel.transformExcelToLucky(files[0], function(exportJson, luckysheetfile){
                console.log(exportJson, 'exportJson')
                if(exportJson.sheets==null || exportJson.sheets.length==0){
                    alert("Failed to read the content of the excel file, currently does not support xls files!");
                    return;
                }
                _this.sheets = exportJson.sheets
                window.luckysheet.destroy();

                window.luckysheet.create({
                    container: 'luckysheet', //luckysheet is the container id
                    showinfobar:false,
                    lang: 'zh',
                    data:exportJson.sheets,
                    title:exportJson.info.name,
                    userInfo:exportJson.info.name.creator,
                    hook: {
                        rangeSelect: function(sheet, range) {
                            // 框选或者设置选区后触发
                            console.log(range, 'range')
                            // var result = window.luckysheet.getRangeWithFlatten()

                            var rangeValue = window.luckysheet.getRangeValue()
                            console.log(rangeValue, 'rangeValue')
                            var result = window.luckysheet.getRangeAxis()
                            console.log(result, 'result')
                            // window.luckysheet.setRangeValue(rangeValue,{range: result[0]})
                        }
                    }
                });
                setTimeout(() => {
                    if (_this.formParam.meetingPersonName)
                    {
                        _this.cellData = _this.getCellData(_this.formParam.meetingPersonName)
                        console.log(_this.cellData, '_this.cellData')
                        _this.map = JSON.parse(JSON.stringify(_this.cellData))
                        if (_this.formParam.pxfs)
                        {
                            _this.seatingOrder(_this.formParam.pxfs)
                        }
                        else
                        {
                            _this.addValue(_this.formParam.meetingPersonName)
                        }
                    }
                }, 1000)
            });
        },
        getCellData(value)
        {
            var resultData;
            var personList = value.split(',');
            var persons = []
            if (this.vacationPersons.length > 0)
            {
                personList.map(item => {
                    this.vacationPersons.map(per => {
                        if (item != per.name)
                        {
                            persons.push(item)
                        }
                    })
                })
                personList = persons
            }
            this.personList = personList;
            var zwwz = this.formParam.zwwz || '1';  // 座位位置 0 左边  1 中间  2 右边
            var personNum = value.split(',').length  // 参会人员数量
            if (this.sheets.length == 0) return [];
            var celldata = this.sheets[0].celldata;
            var type = zwwz == '1' ? 'C' : zwwz == '0' ? 'L' : 'R'
            resultData = celldata.filter(item => item.v.v == type)
            console.log(resultData, 'resultData')
            console.log(celldata, 'celldata')
            resultData.map((item,index) => {
                item.isRefresh = false
                if (index < personList.length)
                {
                    item.isRefresh = true
                    item.v.m = personList[index]
                }
                else
                {
                    item.v.m = ''
                }
                // item.v.m = personList[index] || type
            })
            return resultData;
        },
        // 选择参会人员添加到表格
        addValue(value)
        {
            this.cellData = this.getCellData(value)
            console.log("选择参会人员添加到表格",this.cellData);
            this.map = JSON.parse(JSON.stringify(this.cellData))
            this.cellData.map(item => {
                let options = { isRefresh: item.isRefresh }
                window.luckysheet.setCellValue(item.r, item.c, item.v, options)
            })
            window.luckysheet.refreshFormula();
        },
        // 排序
        seatingOrder(type)
        {
            console.log(type, 'type')
            if (this.formParam.meetingPersonName == '')
            {
                this.$message.warning('请先选择参会人员')
                return
            }
            // console.log("参会人员--->",this.map);
            // this.map.map(item => {
            //     window.luckysheet.setCellValue(item.r, item.c, '')
            // })
            var resultData = []
            if (Number(type) == 0)
            {
                // S型排列
                var celldata = JSON.parse(JSON.stringify(this.cellData))
                var data = this.formatter(celldata)

                resultData = data
            }
            else if (Number(type) == 1)
            {
                // S型隔位排列
                var celldata = JSON.parse(JSON.stringify(this.cellData))
                var data = this.formatter1(celldata)

                // return
                resultData = data
                this.map = resultData;
            }
            else if (Number(type) == 2)
            {
                // 中间至两侧排列
                var celldata = JSON.parse(JSON.stringify(this.cellData))
                let map = new Map()
                celldata.forEach(item => {
                    if (map.has(item.r)) 
                    {
                        map.set(item.r, map.get(item.r).concat(item))
                    } 
                    else 
                    {
                        map.set(item.r, [item])
                    }
                })
                var personList = this.personList;
                let evenIndex = 0;
                let oddIndex = 1;
                let start = true;
                one:
                for (const item of map.entries()) {
                    let rows = item[1];
                    if(!start){
                        console.log("------------------->0",rows);
                        evenIndex = 0;
                        oddIndex = 1;
                        console.log("------------------->1",rows);
                    }
                    var mid = Math.floor(rows.length / 2)
                    for(let j=0; j<rows.length; j++){
                        if (j == mid)
                        {
                            rows[j].v.m = personList[evenIndex]
                            evenIndex++;
                        }
                        if (j > mid)
                        {
                            rows[j].v.m = personList[evenIndex * 2]
                            evenIndex++;
                            if (evenIndex >= personList.length)
                            {
                                break one;
                            }
                        }
                        if (j < mid) {
                            rows[(mid - 1) - j].v.m = personList[oddIndex + j]
                            oddIndex++;
                            if (oddIndex >= personList.length)
                            {
                                // break one;
                                rows[(mid - 1) - j].v.m = rows[j].v.v;
                            }
                        }
                    }
                    personList = personList.slice(rows.length, personList.length)
                    console.log(personList, 'personList')
                    start = !start;
                }
                resultData = celldata;
                this.map = resultData
            }
            else if (Number(type) == 3)
            {
                // 中间至两侧隔位排列
                var celldata = JSON.parse(JSON.stringify(this.cellData))
                let map = new Map()
                celldata.forEach(item => {
                    if (map.has(item.r)) 
                    {
                        map.set(item.r, map.get(item.r).concat(item))
                    } 
                    else 
                    {
                        map.set(item.r, [item])
                    }
                })
                console.log('map', map)
                let evenIndex = 0;
                let oddIndex = 0;
                let index = 0;
                let i = 0;
                let start = true;
                one:
                for (const item of map.entries()) {
                    let rows = item[1];
                    var mid = Math.floor(rows.length / 2)
                    console.log(mid, 'mid')
                    if(!start){
                        console.log("------------------->0",mid, index);
                        if (this.formParam.zwwz == '1')
                        {
                            evenIndex = mid;
                            rows = rows;
                            index = mid
                        }
                        else
                        {
                            oddIndex = evenIndex;
                            evenIndex = index;
                            rows = rows;
                        }
                        console.log("------------------->1",rows, evenIndex);
                    }
                    else
                    {
                        if (mid % 2 == 0) {
                            oddIndex = evenIndex
                            evenIndex = index
                        }
                    }
                    for(let j=0; j<rows.length; j++){
                        if (this.formParam.zwwz == '1') // 中间
                        {
                            if (j == mid)
                            {
                                rows[j].v.m = this.personList[evenIndex]
                                evenIndex++;
                                index++;
                                i++;
                            }
                            if (j < mid)
                            {
                                if (j % 2 == 1)
                                {
                                    rows[(mid - 1) - j].v.m = this.personList[index];
                                    index++;
                                    i++;
                                }
                                else
                                {
                                    rows[j].v.m = rows[j].v.v
                                    index++;
                                }
                            }
                            if (j > mid)
                            {
                                if (j % 2 == 1)
                                {
                                    rows[j].v.m = this.personList[evenIndex];
                                    evenIndex++;
                                    index++
                                    i++;
                                    console.log(i, 'i')
                                    if (i >= this.personList.length)
                                    {
                                        break one;
                                    }
                                }
                                else
                                {
                                    rows[j].v.m = rows[j].v.v
                                    evenIndex++;
                                    index++;
                                }
                            }
                        }
                        else
                        {
                            if (j == mid)
                            {
                                rows[j].v.m = this.personList[evenIndex]
                                evenIndex++;
                                index++;
                                i++;
                            }
                            if (mid % 2 == 0)
                            {
                                if (j > mid)
                                {
                                    if (j % 2 == 0)
                                    {
                                        rows[j].v.m = this.personList[evenIndex];
                                        evenIndex++;
                                        index++;
                                        i++;
                                        if (i >= this.personList.length)
                                        {
                                            break one;
                                        }
                                    }
                                    else
                                    {
                                        rows[j].v.m = rows[j].v.v
                                        evenIndex++
                                    }
                                }
                                if (j < mid) 
                                {
                                    if (j % 2 == 0)
                                    {
                                        rows[(mid - 2) - j].v.m = this.personList[oddIndex + j];
                                        index++;
                                        i++;
                                    }
                                    else
                                    {
                                        rows[j].v.m = rows[j].v.v
                                    }
                                }
                            }
                            if (mid % 2 == 1) 
                            {
                                if (j > mid)
                                {
                                    if (j % 2 == 1)
                                    {
                                        rows[j].v.m = this.personList[evenIndex];
                                        evenIndex++;
                                        index++;
                                        i++;
                                        if (i >= this.personList.length)
                                        {
                                            break one;
                                        }
                                    }
                                    else
                                    {
                                        rows[j].v.m = rows[j].v.v
                                        evenIndex++;
                                    }
                                }
                                if (j < mid) 
                                {
                                    if (j % 2 == 1)
                                    {
                                        rows[(mid - 1) - j].v.m = this.personList[evenIndex + j];
                                        // oddIndex++;
                                        index++;
                                        i++;
                                        // if (index >= this.personList.length)
                                        // {
                                        //     break one;
                                        // }
                                    }
                                    else
                                    {
                                        rows[j].v.m = rows[j].v.v
                                    }
                                }
                            }
                        }
                    }
                    start = !start;
                }
                // var datas = celldata.filter(item => item.v.m != 'L')
                // console.log(datas, 'datas')
                console.log(celldata, 'celldata')
                resultData = celldata
                this.map = resultData
            }

            console.log(resultData, 'resultData')
            resultData.map(item => {
                window.luckysheet.setCellValue(item.r, item.c, item.v, { isRefresh: item.isRefresh })
            })
        },
        // 格式化S排列数据
        formatter(data)
        {
            let map = new Map()
            data.forEach(item => {
                if (map.has(item.r))
                {
                    map.set(item.r, map.get(item.r).concat(item))
                }
                else
                {
                    map.set(item.r, [item])
                }
            })
            var items = []
            for (const item of map.entries()) {
                items.push(item)
            }
            items.map((item, index) => {
                if (index %2 == 1)
                {
                    var numArr = []
                    item[1].map(tmp => {
                        numArr.push(tmp.c)
                    })
                    numArr = numArr.reverse()
                    numArr.map((num, numIndex) => {
                        item[1].map(child => {
                            item[1][numIndex].c = num
                        })
                    })
                }
            })

            return data;
        },
        // 格式化S隔位排列数据
        formatter1(data)
        {
            console.log("格式化S隔位排列数据---",data);
            let map = new Map()
            //分离每一行数据
            data.forEach(item => {
                if (map.has(item.r)) 
                {
                    map.set(item.r, map.get(item.r).concat(item))
                } 
                else 
                {
                    map.set(item.r, [item])
                }
            })

            console.log("map数据",map);
            let index = 0;
            let start = true;
            one:
            for (const item of map.entries()) {
                let rows = item[1];
                if(!start){
                    console.log("------------------->0",rows);
                    rows = rows.reverse();
                    console.log("------------------->1",rows);
                }
                for(let j=0; j<rows.length; j++){
                    
                    if(j % 2 == 0){
                        console.log("----------000000--------->1",rows);
                        console.log("----------jjjjjj-------->1",j);
                        rows[j].v.m = this.personList[index];
                        index++;
                        if(index >= this.personList.length){
                            break one;
                        }
                    }
                    else{
                        // rows[j].v.m = rows[j].v.v;
                        rows[j].v.m = '';
                    }
                }
                start = !start;
            }
            console.log(data, 'data')
            return data;
        }
    },
}
</script>

<style lang="scss" scoped>
.seat-wrap {
    height: 520px;
    ::v-deep .luckysheet {
        width: 98% !important;
    }
}
</style>